// preload.js
const { contextBridge, ipcRenderer } = require('electron');
//暴漏了一个electronAPI 给渲染进程调用
contextBridge.exposeInMainWorld('electronAPI', {
  ///异步返回 在vue中使用的代码
  //  console.log('window.electron='+window.electronAPI);
  //  window.electronAPI.send("insert","wo lai le");
  //  window.electronAPI.receive("insert", (msg) => {
  //    console.log(`Received ${msg} from main process`);
  //  });
  send:  (channel, data) => {
    console.log('preload.js send：'+channel+"=="+data);
    ipcRenderer.send(channel, data);
  },
  //返回结果
  receive: (channel, func) => {
    //渲染进程
    console.log('preload.js receive:'+channel+"=="+func);
    //判断是否已经监听
    if (ipcRenderer.listenerCount(channel) > 0) {
      return;
    }
    ipcRenderer.on(channel, (event, ...args) => func(...args));
    // ipcRenderer.on(channel,function(event,...args){
    //   console.log('preload.js receive:'+channel+"=="+a);
    // });
  },
  //移除监听
  removeListener: (channel) => {
    ipcRenderer.removeListener(channel);
  },
  //移除全部监听
  removeAllListeners: () => {
    ipcRenderer.removeAllListeners();
  },
  //异步返回结果 和上面相反
   //异步返回 在vue中使用的代码
  //  query2(){
  //   window.electronAPI.sendSynchronization('query2', 'bai').then((data) => {
  //     console.log('data='+data);
  //     console.log('data='+JSON.stringify(data));
  //   });
  // }
  sendSynchronization : async (channel,key) =>{
    try {
      var result = await ipcRenderer.invoke(channel, key);
      console.log('Received result:', result);
    } catch (error) {
      console.error('Error requesting data from main process:', error);
    }
    return result;
  }
});




